package com.arrogames.lib.ash.rendering {
	import ash.core.Engine;
	import ash.core.NodeList;
	import ash.core.System;
	
	import starling.display.DisplayObjectContainer;
	
	public class RenderingSystem extends System {
		
		protected var container:DisplayObjectContainer;
		protected var nodes:NodeList;
		
		public function RenderingSystem(container:DisplayObjectContainer) {
			super();
			this.container = container;
		}
		
		override public function addToEngine(engine:Engine):void {
			super.addToEngine(engine);
			
			nodes = engine.getNodeList(RenderNode);
			var node:RenderNode;
			for (node = nodes.head; node; node = node.next) {
				renderNodeAdded(node);
			}
			
			nodes.nodeAdded.add(renderNodeAdded);
			nodes.nodeRemoved.add(renderNodeRemoved);
		}
		
		override public function removeFromEngine(engine:Engine):void {
			var node:RenderNode;
			for (node = nodes.head; node; node = node.next) {
				renderNodeRemoved(node);
			}
			nodes = null;
		}
		
		override public function update(time:Number):void {
			var node:RenderNode;
			for (node = nodes.head; node; node = node.next) {
				updatePosition(node);
			}
		}
		
		protected function renderNodeAdded(node:RenderNode):void {
			container.addChild(node.display.graphic);
		}
		
		protected function renderNodeRemoved(node:RenderNode):void {
			container.removeChild(node.display.graphic);
		}
		
		protected function updatePosition(node:RenderNode):void {
			node.display.graphic.x = node.position.x;
			node.display.graphic.y = node.position.y;
		}
		
	}
}